package com.ericsson.common.quartz.service;

import com.ericsson.enap.modules.monitor.entity.EpcCron;
import com.ericsson.common.quartz.job.MyJob;
import com.ericsson.common.quartz.task.ManualTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author : 89007337.zhuyanpeng
 * @date :Create in  2019/8/3- 22:15
 **/
@Component
public class QuartzTableManager {

    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;

    /***************************  此三者均可复用，类似于 Factory 一样。故提出做公用 *********************/
    //调度器
    private static Scheduler scheduler;
    //JobBuilder
    private static JobBuilder jobBuilder;
    //触发器Builder
    private static TriggerBuilder<Trigger> triggerBuilder ;


    //毫秒的间隔时间
    private static final Integer MILLISECONDS=1000;

    @PostConstruct
    public void init(){
        //因为Job 被自己给实现了故此处应去指定对应的Job类去创建一个调度器
        QuartzTableManager.jobBuilder= JobBuilder.newJob(MyJob.class);
        QuartzTableManager.scheduler = schedulerFactoryBean.getScheduler();
        triggerBuilder = TriggerBuilder.newTrigger();
    }


    /**
     * @Description: 手动添加一个定时任务
     * @param jobName          任务名
     * @param jobGroupName     任务组名
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClass         任务
     * @param cron             时间设置，参考quartz说明文档
     * @param quartzTask       task参数
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void addManualTaskJob(String jobName, String jobGroupName,
                             String triggerName, String triggerGroupName, Class jobClass, String cron, ManualTask quartzTask) {
        try {
            JobDataMap jobMap=new JobDataMap();
            jobMap.put("manualTask", quartzTask);
            // 任务名，任务组，任务执行类
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName)
                    .usingJobData(jobMap)
                    .build();
            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    /**
     * 后台管理方式增加任务
     *
     * @param :com.study.www.model.config
     * @Date: 2018/2/26 9:57
     * @return: void
     */
     void addJob(EpcCron config) throws SchedulerException {
        //得到调度器
        JobKey jobKey = this.getJobKey(config);
        //获得触发器
        TriggerKey triggerKey = TriggerKey.triggerKey(config.getName(), config.getGroup());
        Trigger trigger = scheduler.getTrigger(triggerKey);
        //判断触发器是否存在（如果存在说明之前运行过但是在当前被禁用了，如果不存在说明一次都没运行过）
        if (trigger == null) {
            //新建一个工作任务 指定任务类型为串接进行的
            JobDetail jobDetail = jobBuilder.withIdentity(jobKey).build();
            //将工作添加到工作任务当中去
            JobDataMap jobDataMap = jobDetail.getJobDataMap();
            jobDataMap.put("SCHEDULEJOB", config);
            trigger = getTrigger(config, triggerKey);
            //在调度器中将触发器和任务进行组合
            scheduler.scheduleJob(jobDetail, trigger);
        } else {
            //按照新的规则进行
            trigger = getTrigger(config, triggerKey);
            //重启
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    }

    /**
    * 注意 simpleTrigger 和 cronTrigger 互斥只可以选择一个
    */
    private Trigger getTrigger(EpcCron config, TriggerKey triggerKey ){
        Trigger trigger =null;
        //将cron表达式进行转换
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(config.getCron());
        trigger = triggerBuilder.withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
        return trigger;
    }

    /**
     * 删除任务
     *
     * @param : com.study.www.model.config
     * @Date: 2018/2/24 18:23
     * @return: void
     */
     void deleteJob(EpcCron config) throws SchedulerException {
        //找到key值
        JobKey jobKey = this.getJobKey(config);
        //从触发器找到此任务然后进行删除
        scheduler.deleteJob(jobKey);
    }

    /**
     * 根据name和group得到任务的key
     *
     * @param :com.study.www.model.config
     * @Date: 2018/2/24 18:27
     * @return: org.quartz.JobKey
     */
     JobKey getJobKey(EpcCron config) {
        return getJobKey(config.getName(), config.getGroup());
    }

     JobKey getJobKey(String name, String group) {
        return JobKey.jobKey(name, group);
    }
}
